<template>
  <div class="drop-wrapper">
    <div
      class="drop-box"
      :class="{ over: classList.over }"
      ref="dropRef"
      id="drop-box"
    >
      <span v-if="fileList.length === 0">拖动文件到这里,开始上传</span>
      <ul v-else>
        <li v-for="container in fileList" :key="container.filename">
          {{ container.filename }}
        </li>
      </ul>
    </div>

    <button type="button" id="btn-submit" @click="submitUpload">上 传</button>
    <div class="process" v-if="fileList[0] && fileList[0].hash">
      <div class="item" v-for="container in fileList" :key="container.hash">
        {{ container.filename }}：
        {{ container.uploadPercentage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, reactive, watch } from "vue";
import {
  uploadChunks,
  verifyUpload,
  structureChunkData,
} from "../hook/useUpload";
import { calculateHash } from "../hook/useCalculateHash";
import { useUploadPercentage } from "../hook/useProcess";
import { createFileChunk } from "../hook/useFileHandler";
const CHUNK_SIZE = 1024 * 1024 * 10;
export default {
  setup() {
    const dropRef = ref(null);
    const classList = reactive({});
    const fileListRef = ref([]);
    const dataRef = ref([]);
    const hashPercentageRef = ref("");

    onMounted(() => {
      // 在drop元素上松开手
      document.addEventListener("drop", function (e) {
        e.preventDefault();
      });

      // 拖拽到drop元素上
      dropRef.value.addEventListener("dragover", function (e) {
        classList.over = true;
        e.preventDefault();
      });

      // 没松手，拖拽离开drop元素
      dropRef.value.addEventListener("dragleave", function (e) {
        classList.over = false;
        e.preventDefault();
      });

      // 获取存储需要上传文件
      dropRef.value.addEventListener(
        "drop",
        function (e) {
          e.preventDefault(); //取消浏览器默认拖拽效果

          var files = e.dataTransfer.files; //获取拖拽中的文件对象
          var len = files.length; //用来获取文件的长度（其实是获得文件数量）

          //检测是否是拖拽文件到页面的操作
          if (!len) {
            classList.over = false;
            return;
          } else if (len > 6) {
            classList.over = false;
            return alert("最多一次性上传六个文件");
          }
          fileListRef.value = [...files].map((item) => ({
            file: item,
            filename: item.name,
            size: item.size,
          }));
          classList.over = true;
          window.willUploadFileList = files;
        },
        false
      );
    });
    const submitUpload = async () => {
      for (let i = 0; i < fileListRef.value.length; i++) {
        const container = fileListRef.value[i];

        const file = container.file;
        let fileChunkList = [];

        //根据container.file生成切片数组
        fileChunkList[i] = createFileChunk(file, CHUNK_SIZE);

        // 计算文件hash
        container.hash = await calculateHash(
          hashPercentageRef,
          fileChunkList[i]
        );

        // 构建要上传的切片数组数据结构
        dataRef.value[i] = structureChunkData(fileChunkList[i], container);

        // 计算总进度（百分之多少）
        container.uploadPercentage = useUploadPercentage(dataRef.value[i], container);

        // 上传切片
        await uploadChunks(dataRef.value[i], container);
      }
    };
    return {
      dropRef,
      classList: classList,
      submitUpload,
      fileList: fileListRef,
    };
  },
};
</script>

<style lang="css" scoped>
.drop-wrapper .drop-box {
  width: 200px;
  height: 200px;
  padding: 20px;
  background-color: rgba(23, 32, 32, 0.3);
  font-size: 12px;
  box-sizing: border-box;

  color: #fff;
}
.drop-wrapper .drop-box span {
  display: inline-block;
}
.drop-wrapper .drop-box ul {
  padding: 0;
  margin: 0;
}
.drop-wrapper .drop-box li {
  list-style: none;
}
.drop-box.over {
  background-color: rgba(25, 64, 64, 0.6);
}
</style>